<template>
    <page-panel
        header-title="动态表单流程查看审批"
        style="height: calc(100% - 40px);border-radius: 10px;"
    >
        <audit-container
            :infos="infos"
            :before-complete="beforeComplete"
            return-name="ProdEnvironmentReleaseList"
            @ready="getModel"
        >
            <div style="width:100%;height: 50px; display: flex;flex-direction: row;justify-content: flex-start;margin:10px 0;align-items: center;">
                <div style="width: 140px;">
                    项目名称：{{ projectName }}
                </div>
            </div>
            <v-form-render
                v-if="formJson != null"
                :form-json="formJson"
                :form-data="formData"
                :option-data="optionData"
                :preview-state="previewState"
                ref="formRenderer"
            >
            </v-form-render>
            <div style="width:100%;height: 50px; display: flex;flex-direction: row;justify-content: flex-start;margin:10px 0;align-items: center;">
                <div style="width: 140px;">
                    下一节点审批人：
                </div>
                <select-audit
                    style="width: calc(100% - 140px);"
                    :api-fn="fn.auditFn"
                    :show-dept="false"
                    :page-model="model"
                />
            </div>
            <el-footer
                v-if="formJson"
                style="line-height: 60px;float: right;"
            >
                <el-button
                    type="default"
                    @click="handleCancel"
                >取消</el-button>
                <el-button
                    type="primary"
                    @click="handleBack"
                >退回</el-button>
                <el-button
                    type="primary"
                    @click="handleAgree"
                >同意</el-button>
            </el-footer>
        </audit-container>
    </page-panel>
</template>
<script>
import { PRODUCT_APPLY } from "@/constants/businessType";
import { queryById, save, submit, startProcess } from "@/pages/common/api/productionEnvironmentReleaseApi";
import { ModelTemplate } from "./modules/model";
import { cloneDeep } from "lodash";

import ViewMixin from "@/components/mixins/ViewMixin";
import AuditContainer from "@/components/audit/process/AuditContainer";
import FileUpload from "@/components/mainEntrance/FileUpload/index.vue";
// import EditPage from "./EditPage.vue";
import EditPopup from "@/components/audit/process/auditComp/EditPopup.vue";
import ProcessFormItem from "@/components/audit/FormItem/index.vue";
import { parentMixin } from "@/components/audit/FormItem/mixin.js";
import SelectAudit from "@/components/audit/nextAudit/SelectAudit";

export default {
    name: "ViewForm",
    components: {
        AuditContainer,
        FileUpload,
        // EditPage,
        EditPopup,
        ProcessFormItem,
        SelectAudit
    },
    dicts: ["prod_env_apply_reason", "prod_env_apply_type", "prod_env_apply_attach_type"],
    mixins: [ViewMixin, parentMixin],
    data() {
        return {
            fileType: ["doc", "docx", "xls", "xlsx", "pdf", "png", "jpg", "zip", "ppt"],
            model: cloneDeep(ModelTemplate),
            fileList: [],
            infos: {
                businessType: PRODUCT_APPLY,
                processId: ""
            },
            fn: {
                findById: id => queryById(id).then(v => v.data.data)
            },
            fileTypeMap: new Map(),
            dictMap: {},
            formJson: null,
            formData: {},
            optionData: {},
            projectName: '',
            previewState: true,
        };
    },
    computed: {
        applyType() {
            return this.dict.type.prod_env_apply_type.find(item => item.value === this.model.applyType)?.label;
        },
        applyReason() {
            return this.dict.type.prod_env_apply_reason.find(item => item.value === this.model.applyReasonType)?.label;
        }
    },
    watch: {
        // eslint-disable-next-line func-names
        "dict.type.prod_env_apply_attach_type": function (val) {
            val.forEach(item => {
                this.dictMap[item.value] = item.label;
            });
        }
    },
    created() {
        console.log('previewState', this.previewState);

        console.log('view form', this.$route.query);
        if (this.$route.query.formJson != null) {
            this.projectName = this.$route.query.projectName;

            this.formJson = JSON.parse(this.$route.query.formJson)
            this.$nextTick(() => {
                let formData = JSON.parse(this.$route.query.formValue)
                this.$refs.formRenderer.setFormData(formData)
            })
        }
    },
    mounted() { },
    methods: {
        modelOk() {
            // 上传附件审批是否可编辑
            const flag = this.checkEdit("attachType");
            this.model.attachList.forEach(item => {
                const { fileType, filePath, fileName } = item;
                // 解析出attachType
                this.model.attachType.push(fileType);
                if (flag) {
                    // 存入对应的上传文件内容
                    this.$set(this.model, `fileType_${fileType}`, filePath);
                    this.fileTypeMap.set(item.fileType, [{ name: fileName, url: filePath, id: filePath.split(":")[0] }]);
                }
            });
            if (flag) {
                this.model.attachList = [];
            }
            this.itemControlCenter();
        },
        handleCheckBoxChange(val) {
            this.dict.type.prod_env_apply_attach_type.forEach(item => {
                const code = item.value;
                if (!val.includes(code)) {
                    this.model[`fileType_${code}`] = "";
                    this.fileTypeMap.delete(code);
                    this.trimAttachList(code);
                }
            });
        },
        changeFileList(fileList, fileType) {
            if (!fileList || fileList.length === 0) {
                this.model[`fileType_${fileType}`] = "";
                if (this.model.attachList) {
                    // 过滤掉该fileType的数据
                    this.trimAttachList(fileType);
                }
            }
            // 将改文件存到fileTypeMap中，可以保证fileTypeMap中不会存入重复类型的文件
            this.fileTypeMap.set(fileType, fileList);
        },
        trimAttachList(code) {
            // 因为每个类型文件只能上传一个，所以我们这边可以直接把对应code的内容过滤掉
            this.model.attachList = this.model.attachList.filter(item => item.fileType !== code);
        },
        /**
         * 处理之前将编辑字段数据保存到infos.model中
         */
        beforeComplete() {
            console.log('action', this.action);

            // if (this.action && this.action.toLocaleLowerCase() === "view") {
            //     // 查看模式
            //     return true;
            // }
            console.log("this.infos", this.infos);

            // if (this.infos?.editableFormFields?.length) {
            //     // 筛选出当前处理操作可编辑字段
            //     const editFields = this.infos.editableFormFields.filter(item => item.completeEnable).map(item => item.fieldName);
            //     const model = {};
            //     editFields.forEach(item => {
            //         if (item === "attachType") {
            //             // 附件单独处理
            //             const attachList = [];
            //             // 使用字典类型开始遍历
            //             this.dict.type.prod_env_apply_attach_type.forEach(dict => {
            //                 const code = dict.value;
            //                 // 从fileTypeMap中获取数组 遍历
            //                 this.fileTypeMap.get(code)?.forEach(file => {
            //                     const { name, id } = file;
            //                     attachList.push({
            //                         fileName: name,
            //                         filePath: `${id}:${name}`,
            //                         fileType: code
            //                     });
            //                 });
            //             });
            //             this.$set(model, "attachList", attachList);
            //         } else {
            //             this.$set(model, item, this.model[item]);
            //         }
            //     });
            //     this.$set(this.infos, "model", model);
            // }
            // return true;
        },
        /**
         * 处理取消操作
         *
         * @returns 无返回值
         */
        handleCancel() {
            this.$router.push({
                path: "/ProdRelease/ProdEnvironmentReleaseList"
            });
        },
        /**
         * 处理同意操作
         *
         * @returns 无返回值
         */
        handleAgree() {
            console.log('同意操作');

        },
        /**
         * 处理返回按钮点击事件
         *
         * @returns 无返回值
         */
        handleBack() {
            console.log('返回按钮点击事件');

        }

    }
};
</script>
<style scoped lang="less">
@import "@/assets/styles/less/form.less";

.form-layout {
    .form-layout(150px);
}

/deep/ .el-upload {
    width: auto !important;
}
</style>